#include <iostream>
#include <signal.h>
#include "../comm/httplib.h"
#include "./oj_control.hpp"
using namespace httplib;
using namespace NS_CTRL;

// 这个模块是用来设置功能路由转接的
// 主要是获取题目列表，获取题号，判断功能
static contral* ctr_p=nullptr;
void Recover(int signal)
{
    ctr_p->RecoveryMachines();
    std::cout<<"所有的主机都上线了"<<std::endl;
}

int main(int argc, char *argv[])
{
    signal(SIGQUIT, Recover);
    if (argc != 2)
    {
        std::cout << argv[0] << " port" << std::endl;
        return -2;
    }
    Server ser;
    contral crl;
    ctr_p=&crl;

    // 获取题目列表
    ser.Get("/all_questions", [&crl](const Request &req, Response &resp)
            {
        std::string html; 
        crl.AllQuetsion(&html);
        resp.set_content(html, "text/html;charset=utf-8"); });

    // 获取题目编号
    // 正则匹配
    ser.Get(R"(/question/(\d+))", [&crl](const Request &req, Response &resp)
            {
        std::string num=req.matches[1];
        std::string html;
        crl.OneQuestion(num,&html);
        resp.set_content(html,"text/html;charset=utf-8"); });

    // 判断功能
    ser.Post(R"(/judge/(\d+))", [&crl](const Request &req, Response &resp)
             {
        std::string num=req.matches[1];
        std::string resp_html;
        crl.Judge(num,req.body,&resp_html);
        resp.set_content(resp_html,"application/json;charset=utf-8"); });

    ser.set_base_dir("./wwwroot");
    ser.listen("0.0.0.0", std::stoi(argv[1]));
    return 0;
}